package com.jiguang.property.service.impl.userImpl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiguang.property.config.LoginUser;
import com.jiguang.property.dto.UserInfoDTO;
import com.jiguang.property.entity.User;
import com.jiguang.property.handler.GuliException;
import com.jiguang.property.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service("UserDetailsService")
public class UserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService {

    @Autowired
    private UserService ucenterService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfoDTO userInfoDto = new UserInfoDTO();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User userByUsername = ucenterService.getOne(wrapper);
        if (userByUsername == null) {
            QueryWrapper<User> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("email", username);
            User userByEmail = ucenterService.getOne(wrapper1);
            if (userByEmail == null) {
                throw new GuliException(11001, "用户不存在");
            }
            BeanUtil.copyProperties(userByEmail,userInfoDto);
            return new LoginUser(userInfoDto);
        }
        BeanUtil.copyProperties(userByUsername,userInfoDto);
        return new LoginUser(userInfoDto);
    }
}
